﻿Imports System.Data.OleDb
Imports System.Text.RegularExpressions
Imports EASendMail
Public Class frmSendEmail

    Inherits System.Windows.Forms.Form

#Region "NotifyIcon"

    Private Sub frmSendEmail_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        Try
            If Me.WindowState = FormWindowState.Minimized Then
                Me.Visible = False
                NotifyIcon.Visible = True
                NotifyIcon.ShowBalloonTip(1, "SkyCoffee", "SkyCoffee is Still Running!", ToolTipIcon.Info)
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub NotifyIcon_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon.MouseDoubleClick
        Try
            Me.Visible = True
            Me.WindowState = FormWindowState.Normal
            NotifyIcon.Visible = False
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub mnuLaunchApplication_Click(sender As Object, e As EventArgs) Handles mnuLaunchApplication.Click
        Try
            Me.Visible = True
            Me.WindowState = FormWindowState.Normal
            NotifyIcon.Visible = False
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub mnuExitApplication_Click(sender As Object, e As EventArgs) Handles mnuExitApplication.Click
        Application.Exit()
    End Sub
#End Region

    Private m_arCharset(27, 1) As String
    Private m_arAttachment As ArrayList = New ArrayList
    Private m_bcancel As Boolean = False
    Private m_eventtick As Long = 0
    Private m_htmlDoc As mshtml.IHTMLDocument2

    Dim dsEmail As New DataSet()
    Dim intCurrentIndexEmail As Integer = 0
    Dim daEmail As New OleDbDataAdapter()
    Dim connEmail As New OleDbConnection()

    Dim ds As New DataSet()
    Dim intCurrentIndex As Integer = 0
    Dim da As New OleDbDataAdapter()
    Dim conn As New OleDbConnection()

    Dim dsStaff As New DataSet()
    Dim intCurrentIndexStaff As Integer = 0
    Dim daStaff As New OleDbDataAdapter()
    Dim connStaff As New OleDbConnection()

    Dim dsSettings As New DataSet()
    Dim intCurrentIndexSettings As Integer = 0
    Dim daSettings As New OleDbDataAdapter()
    Dim connSettings As New OleDbConnection()

    Dim strEmailID As String
    Dim strServer As String
    Dim RequiresAuthentication As Boolean
    Dim strEmailUsername As String
    Dim strEmailPassword As String
    Dim SSLConnection As Boolean
    Dim strProtocol As String

#Region "EASendMail EventHandler"

    Sub OnIdle(ByVal sender As Object, ByRef cancel As Boolean)
        cancel = m_bcancel
        If Not cancel Then
            Application.DoEvents() 'waiting server reponse or connecting server.
        End If
    End Sub

    Sub OnConnected(ByVal sender As Object, ByRef cancel As Boolean)
        _SetStatus("Connected")
        cancel = m_bcancel
    End Sub


    Sub OnSendingDataStream(ByVal sender As Object, ByVal sent As Integer, ByVal total As Integer, ByRef cancel As Boolean)
        If pgSending.Value = 0 Then
            _SetStatus("Sending ...")
        End If
        _SetProgress(sent, total)
        cancel = m_bcancel
        If sent = total Then
            _SetStatus("Disconnecting ...")
        End If

    End Sub

    Sub OnAuthorized(ByVal sender As Object, ByRef cancel As Boolean)
        _SetStatus("Authorized")
        cancel = m_bcancel
    End Sub

    Sub OnSecuring(ByVal sender As Object, ByRef cancel As Boolean)
        _SetStatus("Securing ...")
        cancel = m_bcancel
    End Sub

#End Region

#Region "Initialize Encoding List"
    Private Sub _InitCharset()
        Dim nIndex As Integer = 0
        Dim defaultEncoding As String = "utf-8" 'System.Text.Encoding.Default.HeaderName

        m_arCharset(nIndex, 0) = "Arabic(Windows)"
        m_arCharset(nIndex, 1) = "windows-1256"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Baltic(ISO)"
        m_arCharset(nIndex, 1) = "iso-8859-4"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Baltic(Windows)"
        m_arCharset(nIndex, 1) = "windows-1257"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Central Euporean(ISO)"
        m_arCharset(nIndex, 1) = "iso-8859-2"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Central Euporean(Windows)"
        m_arCharset(nIndex, 1) = "windows-1250"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Chinese Simplified(GB18030)"
        m_arCharset(nIndex, 1) = "GB18030"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Chinese Simplified(GB2312)"
        m_arCharset(nIndex, 1) = "gb2312"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Chinese Simplified(HZ)"
        m_arCharset(nIndex, 1) = "hz-gb-2312"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Chinese Traditional(Big5)"
        m_arCharset(nIndex, 1) = "big5"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Cyrillic(ISO)"
        m_arCharset(nIndex, 1) = "iso-8859-5"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Cyrillic(KOI8-R)"
        m_arCharset(nIndex, 1) = "koi8-r"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Cyrillic(KOI8-U)"
        m_arCharset(nIndex, 1) = "koi8-u"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Cyrillic(Windows)"
        m_arCharset(nIndex, 1) = "windows-1251"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Greek(ISO)"
        m_arCharset(nIndex, 1) = "iso-8859-7"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Greek(Windows)"
        m_arCharset(nIndex, 1) = "windows-1253"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Hebrew(Windows)"
        m_arCharset(nIndex, 1) = "windows-1255"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Japanese(JIS)"
        m_arCharset(nIndex, 1) = "iso-2022-jp"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Korean"
        m_arCharset(nIndex, 1) = "ks_c_5601-1987"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Korean(EUC)"
        m_arCharset(nIndex, 1) = "euc-kr"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Latin 9(ISO)"
        m_arCharset(nIndex, 1) = "iso-8859-15"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Thai(Windows)"
        m_arCharset(nIndex, 1) = "windows-874"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Turkish(ISO)"
        m_arCharset(nIndex, 1) = "iso-8859-9"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Turkish(Windows)"
        m_arCharset(nIndex, 1) = "windows-1254"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Unicode(UTF-7)"
        m_arCharset(nIndex, 1) = "utf-7"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Unicode(UTF-8)"
        m_arCharset(nIndex, 1) = "utf-8"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Vietnames(Windows)"
        m_arCharset(nIndex, 1) = "windows-1258"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Western European(ISO)"
        m_arCharset(nIndex, 1) = "iso-8859-1"
        nIndex = nIndex + 1

        m_arCharset(nIndex, 0) = "Western European(Windows)"
        m_arCharset(nIndex, 1) = "Windows-1252"
        nIndex = nIndex + 1

        Dim selectIndex As Integer = 25 'utf-8
        Dim i As Integer = 0
        For i = 0 To nIndex - 1
            cmbEncoding.Items.Add(m_arCharset(i, 0))
            If String.Compare(m_arCharset(i, 1), defaultEncoding, True) = 0 Then
                selectIndex = i
            End If
        Next
        cmbEncoding.SelectedIndex = selectIndex
    End Sub
#End Region

    Private Sub _Init()
        _InitCharset()
        frmSettings._InitProtocols()
        frmSettings._ChangeAuthStatus()
    End Sub

#Region "Sign and encrypt E-mail by digital certificate"
    Private Function _Signencrypt(ByRef oMail As SmtpMail) As Boolean
        If chkDigitalSignature.Checked Then
            Try
                oMail.From.Certificate.FindSubject(oMail.From.Address, _
                  Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
                  "My")
            Catch exp As Exception
                MessageBox.Show("No sign certificate found for <" + oMail.From.Address + ">:" + exp.Message)
                btnSendEmail.Text = "Send"
                _Signencrypt = False
                Exit Function
            End Try
        End If

        Dim count As Integer = 0
        If chkEncrypt.Checked Then
            count = oMail.To.Count
            Dim i As Integer = 0
            For i = 0 To count - 1

                Dim oAddress As MailAddress = oMail.To(i)
                Try

                    oAddress.Certificate.FindSubject(oAddress.Address, _
                     Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
                     "AddressBook")
                Catch ep As Exception
                    Try

                        oAddress.Certificate.FindSubject(oAddress.Address, _
                         Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
                         "My")
                    Catch exp As Exception
                        MessageBox.Show("No encryption certificate found for <" + oAddress.Address + ">:" + exp.Message)
                        _Signencrypt = False
                        Exit Function
                    End Try
                End Try
            Next

            count = oMail.Cc.Count
            For i = 0 To count - 1
                Dim oAddress As MailAddress = oMail.Cc(i)
                Try
                    oAddress.Certificate.FindSubject(oAddress.Address, _
                      Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
                      "AddressBook")
                Catch ep As Exception
                    Try
                        oAddress.Certificate.FindSubject(oAddress.Address, _
                         Certificate.CertificateStoreLocation.CERT_SYSTEM_STORE_CURRENT_USER, _
                         "My")
                    Catch exp As Exception
                        MessageBox.Show("No encryption certificate found for <" + oAddress.Address + ">:" + exp.Message)
                        _Signencrypt = False
                        Exit Function
                    End Try
                End Try
            Next
        End If

        _Signencrypt = True
    End Function

#End Region

#Region "Send E-mail without SMTP server to multiple recipients"
    Private Sub _DirectSend(ByRef oMail As SmtpMail, ByRef oSmtp As SmtpClient)
        Dim recipients As AddressCollection = oMail.Recipients.Copy()
        Dim count As Integer = recipients.Count
        Dim i As Integer

        For i = 0 To count - 1
            Dim errStr As String = ""
            Dim address As MailAddress = recipients(i)

            Dim terminated As Boolean = False
            Try
                oMail.To.Clear()
                oMail.Cc.Clear()
                oMail.Bcc.Clear()

                oMail.To.Add(address)
                Dim oServer As SmtpServer = New SmtpServer("")

                sbStatus.Text = String.Format("Connecting server for {0} ... ", address.Address)
                pgSending.Value = 0
                oSmtp.SendMail(oServer, oMail)
                MessageBox.Show(String.Format("The message to <{0}> was sent to {1} successfully!", _
                    address.Address, _
                    oSmtp.CurrentSmtpServer.Server))

                sbStatus.Text = "Completed"

            Catch exp As SmtpTerminatedException
                errStr = exp.Message
                terminated = True
            Catch exp As SmtpServerException
                errStr = String.Format("Exception: Server Respond: {0}", exp.ErrorMessage)
            Catch exp As System.Net.Sockets.SocketException
                errStr = String.Format("Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message)
            Catch exp As System.ComponentModel.Win32Exception
                errStr = String.Format("Exception: System Error: {0} {1}", exp.ErrorCode, exp.Message)
            Catch exp As System.Exception
                errStr = String.Format("Exception: Common: {0}", exp.Message)
            End Try


            If (terminated) Then
                Exit For
            End If

            If errStr.Length > 0 Then
                MessageBox.Show(String.Format("The message was unable to delivery to <{0}> due to " & vbCrLf & " {1}", _
       address.Address, errStr))
                sbStatus.Text = errStr
            End If
        Next
    End Sub
#End Region

    Public Sub FillFields()
        txtID.Text = ds.Tables(0).Rows(intCurrentIndex).Item("fldDataID").ToString()
        txtFirstName.Text = ds.Tables(0).Rows(intCurrentIndex).Item("fldDataFirstName").ToString()
        txtSurname.Text = ds.Tables(0).Rows(intCurrentIndex).Item("fldDataSurname").ToString()
        txtEmail.Text = ds.Tables(0).Rows(intCurrentIndex).Item("fldDataEmail").ToString()
    End Sub
    Public Sub FillFieldsStaff()
        txtID.Text = dsStaff.Tables(0).Rows(intCurrentIndexStaff).Item("fldDataID").ToString()
        txtFirstName.Text = dsStaff.Tables(0).Rows(intCurrentIndexStaff).Item("fldDataFirstName").ToString()
        txtSurname.Text = dsStaff.Tables(0).Rows(intCurrentIndexStaff).Item("fldDataSurname").ToString()
        txtEmail.Text = dsStaff.Tables(0).Rows(intCurrentIndexStaff).Item("fldDataEmail").ToString()
    End Sub
    Public Sub FillFieldsSettings()
        strEmailID = dsSettings.Tables(0).Rows(intCurrentIndexSettings).Item("fldEmailID").ToString()
        strServer = dsSettings.Tables(0).Rows(intCurrentIndexSettings).Item("fldEmailServer").ToString()
        RequiresAuthentication = dsSettings.Tables(0).Rows(intCurrentIndexSettings).Item("fldEmailRequiresAuthentication").ToString()
        strEmailUsername = dsSettings.Tables(0).Rows(intCurrentIndexSettings).Item("fldEmailUsername").ToString()
        strEmailPassword = dsSettings.Tables(0).Rows(intCurrentIndexSettings).Item("fldEmailPassword").ToString()
        SSLConnection = dsSettings.Tables(0).Rows(intCurrentIndexSettings).Item("fldEmailSSLConnection").ToString()
        strProtocol = dsSettings.Tables(0).Rows(intCurrentIndexSettings).Item("fldEmailProtocol").ToString()
    End Sub
    Private Sub frmSendEmail_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Loads frmMenu
        pnlIcons.Controls.Clear()
        pnlIcons.Controls.Add(frmMenu.pnlIcons)

        'Load ToolTips
        AdminToolTips()

        htmlEditor.Navigate("about:blank")

        m_htmlDoc = CType(htmlEditor.Document.DomDocument, mshtml.IHTMLDocument2)
        m_htmlDoc.designMode = "on"
        InitFonts()

        _Init()

        'Generate Random Reference Number
        Dim intIDLength As Integer  'length of ID
        Dim intCount As Integer     'variable to count to the value of intIDLength
        Dim intAsc As Integer       'random number to choose what the character will be

        Dim strResult As String     'value of the resulting ID

        Dim intNumber As Integer
        Dim intCharacter As Integer 'the resulting character from one cycle

        intIDLength = 6             'length of email id

        Randomize()

        For intNumber = 1 To 1

            'number of random characters to generate
            For intCount = 1 To intIDLength


                'choose random character type to generate numbers
                intAsc = Int((1 * Rnd()) + 1)

                Select Case intAsc

                    Case 1
                        intCharacter = Int((Asc("9") - Asc("0") + 1) * Rnd() + Asc("0"))

                End Select

                'concatenate the resulting character to the previously generated character
                strResult = strResult & Chr(intCharacter)

                'repeat process if the value of "intCount" has not reached "intNumberDigits"
            Next intCount

            strResult = strResult

        Next intNumber

        'display the resulting id in the label
        txtEmailID.Text = strResult

        'Add to database
        connEmail.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;" & _
                "Data Source=|DataDirectory|\SkyCoffee.mdb"

        daEmail.SelectCommand = New OleDbCommand("SELECT * FROM tblEmail")
        daEmail.SelectCommand.Connection = connEmail

        daEmail.InsertCommand = New OleDbCommand("INSERT INTO tblEmail(fldEmailID, fldEmailFrom, fldEmailTo, fldEmailCC, fldEmailSubject, fldEmailEncoding, fldEmailDigitalSignature, fldEmailEncrypt, fldEmailAttachments, fldEmail) VALUES(@fldEmailID,@fldEmailFrom,@fldEmailTo,@fldEmailCC,@fldEmailSubject,@fldEmailEncoding,@fldEmailDigitalSignature,@fldEmailEncrypt,@fldEmailAttachments,@fldEmail)")
        daEmail.InsertCommand.Connection = connEmail
        daEmail.InsertCommand.Parameters.Add("@fldEmailID", OleDbType.Numeric, 6, "fldEmailID")
        daEmail.InsertCommand.Parameters.Add("@fldEmailFrom", OleDbType.VarChar, 40, "fldEmailFrom")
        daEmail.InsertCommand.Parameters.Add("@fldEmailTo", OleDbType.VarChar, 40, "fldEmailTo")
        daEmail.InsertCommand.Parameters.Add("@fldEmailCC", OleDbType.VarChar, 40, "fldEmailCC")
        daEmail.InsertCommand.Parameters.Add("@fldEmailSubject", OleDbType.VarChar, 40, "fldEmailSubject")
        daEmail.InsertCommand.Parameters.Add("@fldEmailEncoding", OleDbType.VarChar, 40, "fldEmailEncoding")
        daEmail.InsertCommand.Parameters.Add("@fldEmailDigitalSignature", OleDbType.Boolean, 40, "fldEmailDigitalSignature")
        daEmail.InsertCommand.Parameters.Add("@fldEmailEncrypt", OleDbType.Boolean, 40, "fldEmailEncrypt")
        daEmail.InsertCommand.Parameters.Add("@fldEmailAttachments", OleDbType.VarChar, 40, "fldEmailAttachments")
        daEmail.InsertCommand.Parameters.Add("@fldEmail", OleDbType.VarChar, 140, "fldEmail")

        daEmail.Fill(dsEmail)

        'Retrieve from database tblCandidatesRetrieveDataForEmail
        conn.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;" & _
                "Data Source=|DataDirectory|\SkyCoffee.mdb"

        da.SelectCommand = New OleDbCommand("SELECT * FROM tblCandidatesRetrieveDataForEmail")
        da.SelectCommand.Connection = conn

        da.UpdateCommand = New OleDbCommand("UPDATE tblCandidatesRetrieveDataForEmail SET fldDataFirstName = @fldDataFirstName, fldDataSurname = @fldDataSurname, fldDataEmail = @fldDataEmail WHERE fldDataID = @fldDataID")
        da.UpdateCommand.Connection = conn
        da.UpdateCommand.Parameters.Add("@fldDataFirstName", OleDbType.VarChar, 40, "fldDataFirstName")
        da.UpdateCommand.Parameters.Add("@fldDataSurname", OleDbType.VarChar, 40, "fldDataSurname")
        da.UpdateCommand.Parameters.Add("@fldDataEmail", OleDbType.VarChar, 40, "fldDataEmail")

        da.UpdateCommand.Parameters.Add("@fldDataID", OleDbType.Numeric, 6, "fldDataID")

        da.InsertCommand = New OleDbCommand("INSERT INTO tblCandidatesRetrieveDataForEmail(fldDataID, fldDataFirstName, fldDataSurname, fldDataEmail) VALUES(@fldDataID,@fldDataFirstName,@fldDataSurname,@fldDataEmail)")
        da.InsertCommand.Connection = conn
        da.InsertCommand.Parameters.Add("@fldDataFirstName", OleDbType.VarChar, 40, "fldDataFirstName")
        da.InsertCommand.Parameters.Add("@fldDataSurname", OleDbType.VarChar, 40, "fldDataSurname")
        da.InsertCommand.Parameters.Add("@fldDataEmail", OleDbType.VarChar, 40, "fldDataEmail")

        da.InsertCommand.Parameters.Add("@fldDataID", OleDbType.Numeric, 6, "fldDataID")

        da.Fill(ds)

        If ds.Tables(0).Rows.Count > 0 Then 'Check to see if the table is empty
            FillFields()
        Else
            MsgBox("No records exist in database")
        End If

        'Retrieve from database tblStaffRetrieveDataForEmail
        connStaff.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;" & _
                "Data Source=|DataDirectory|\SkyCoffee.mdb"

        daStaff.SelectCommand = New OleDbCommand("SELECT * FROM tblStaffRetrieveDataForEmail")
        daStaff.SelectCommand.Connection = connStaff

        daStaff.UpdateCommand = New OleDbCommand("UPDATE tblStaffRetrieveDataForEmail SET fldDataFirstName = @fldDataFirstName, fldDataSurname = @fldDataSurname, fldDataEmail = @fldDataEmail WHERE fldDataID = @fldDataID")
        daStaff.UpdateCommand.Connection = connStaff
        daStaff.UpdateCommand.Parameters.Add("@fldDataFirstName", OleDbType.VarChar, 40, "fldDataFirstName")
        daStaff.UpdateCommand.Parameters.Add("@fldDataSurname", OleDbType.VarChar, 40, "fldDataSurname")
        daStaff.UpdateCommand.Parameters.Add("@fldDataEmail", OleDbType.VarChar, 40, "fldDataEmail")

        daStaff.UpdateCommand.Parameters.Add("@fldDataID", OleDbType.Numeric, 6, "fldDataID")

        daStaff.InsertCommand = New OleDbCommand("INSERT INTO tblStaffRetrieveDataForEmail(fldDataID, fldDataFirstName, fldDataSurname, fldDataEmail) VALUES(@fldDataID,@fldDataFirstName,@fldDataSurname,@fldDataEmail)")
        daStaff.InsertCommand.Connection = connStaff
        daStaff.InsertCommand.Parameters.Add("@fldDataFirstName", OleDbType.VarChar, 40, "fldDataFirstName")
        daStaff.InsertCommand.Parameters.Add("@fldDataSurname", OleDbType.VarChar, 40, "fldDataSurname")
        daStaff.InsertCommand.Parameters.Add("@fldDataEmail", OleDbType.VarChar, 40, "fldDataEmail")

        daStaff.InsertCommand.Parameters.Add("@fldDataID", OleDbType.Numeric, 6, "fldDataID")

        daStaff.Fill(dsStaff)

        If dsStaff.Tables(0).Rows.Count > 0 Then 'Check to see if the table is empty
            FillFieldsStaff()
        Else
            MsgBox("No records exist in database")
        End If

        'Retrieve from database tblEmailSettings
        connSettings.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;" & _
                "Data Source=|DataDirectory|\SkyCoffee.mdb"

        daSettings.SelectCommand = New OleDbCommand("SELECT * FROM tblEmailSettings")
        daSettings.SelectCommand.Connection = connSettings

        daSettings.UpdateCommand = New OleDbCommand("UPDATE tblEmailSettings SET fldEmailServer = @fldEmailServer, fldEmailRequiresAuthentication = @fldEmailRequiresAuthentication, fldEmailUsername = @fldEmailUsername, fldEmailPassword = @fldEmailPassword, fldEmailSSLConnection = @fldEmailSSLConnection, fldEmailProtocol = @fldEmailProtocol WHERE fldEmailID = @fldEmailID")
        daSettings.UpdateCommand.Connection = connSettings
        daSettings.UpdateCommand.Parameters.Add("@fldEmailServer", OleDbType.VarChar, 40, "fldEmailServer")
        daSettings.UpdateCommand.Parameters.Add("@fldEmailRequiresAuthentication", OleDbType.Boolean, 40, "fldEmailRequiresAuthentication")
        daSettings.UpdateCommand.Parameters.Add("@fldEmailUsername", OleDbType.VarChar, 40, "fldEmailUsername")
        daSettings.UpdateCommand.Parameters.Add("@fldEmailPassword", OleDbType.VarChar, 40, "fldEmailPassword")
        daSettings.UpdateCommand.Parameters.Add("@fldEmailSSLConnection", OleDbType.Boolean, 40, "fldEmailSSLConnection")
        daSettings.UpdateCommand.Parameters.Add("@fldEmailProtocol", OleDbType.VarChar, 40, "fldEmailProtocol")

        daSettings.UpdateCommand.Parameters.Add("@fldEmailID", OleDbType.Numeric, 6, "fldEmailID")

        daSettings.InsertCommand = New OleDbCommand("INSERT INTO tblEmailSettings(fldEmailID, fldEmailServer, fldEmailRequiresAuthentication, fldEmailUsername, fldEmailPassword, fldEmailSSLConnection, fldEmailProtocol) VALUES(@fldEmailID,@fldEmailServer,@fldEmailRequiresAuthentication,@fldEmailUsername,@fldEmailPassword,@fldEmailSSLConnection,@fldEmailProtocol)")
        daSettings.InsertCommand.Connection = connSettings
        daSettings.InsertCommand.Parameters.Add("@fldEmailServer", OleDbType.VarChar, 40, "fldEmailServer")
        daSettings.InsertCommand.Parameters.Add("@fldEmailRequiresAuthentication", OleDbType.Boolean, 40, "fldEmailRequiresAuthentication")
        daSettings.InsertCommand.Parameters.Add("@fldEmailUsername", OleDbType.VarChar, 40, "fldEmailUsername")
        daSettings.InsertCommand.Parameters.Add("@fldEmailPassword", OleDbType.VarChar, 40, "fldEmailPassword")
        daSettings.InsertCommand.Parameters.Add("@fldEmailSSLConnection", OleDbType.Boolean, 40, "fldEmailSSLConnection")
        daSettings.InsertCommand.Parameters.Add("@fldEmailProtocol", OleDbType.VarChar, 40, "fldEmailProtocol")

        daSettings.InsertCommand.Parameters.Add("@fldEmailID", OleDbType.Numeric, 6, "fldEmailID")

        daSettings.Fill(dsSettings)

        If dsSettings.Tables(0).Rows.Count > 0 Then 'Check to see if the table is empty
            FillFieldsSettings()
        Else
            MsgBox("No records exist in database")
        End If

    End Sub
    Public Sub AddNewRecord()
        'Reset form fields
        txtEmailID.Text = ""
        txtFrom.Text = ""
        txtTo.Text = ""
        txtCC.Text = ""
        txtSubject.Text = ""
        cmbEncoding.SelectedIndex = -1
        chkDigitalSignature.Checked = False
        chkEncrypt.Checked = False
        txtAttachments.Text = ""
        cmbFont.SelectedIndex = -1
        cmbSize.SelectedIndex = -1

        txtFrom.Focus()

        'Generate Random Reference Number
        Dim intIDLength As Integer  'length of ID
        Dim intCount As Integer     'variable to count to the value of intIDLength
        Dim intAsc As Integer       'random number to choose what the character will be

        Dim strResult As String     'value of the resulting ID

        Dim intNumber As Integer
        Dim intCharacter As Integer 'the resulting character from one cycle

        intIDLength = 6             'length of email id

        Randomize()

        For intNumber = 1 To 1

            'number of random characters to generate
            For intCount = 1 To intIDLength


                'choose random character type to generate numbers
                intAsc = Int((1 * Rnd()) + 1)

                Select Case intAsc

                    Case 1
                        intCharacter = Int((Asc("9") - Asc("0") + 1) * Rnd() + Asc("0"))

                End Select

                'concatenate the resulting character to the previously generated character
                strResult = strResult & Chr(intCharacter)

                'repeat process if the value of "intCount" has not reached "intNumberDigits"
            Next intCount

            strResult = strResult

        Next intNumber

        'display the resulting id in the label
        txtEmailID.Text = strResult
    End Sub

    Private Sub btnSendEmail_Click(sender As Object, e As EventArgs) Handles btnSendEmail.Click
        'Validate that all fields have been filled in correctly
        Dim patternEmailAddress As String = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|biz|info|name)\b"
        Dim regexEmailAddress As New Regex(patternEmailAddress)

        If regexEmailAddress.IsMatch(txtFrom.Text) = False Then
            MsgBox("Please enter a valid email address")
            txtFrom.Focus()
        ElseIf regexEmailAddress.IsMatch(txtTo.Text) = False Then
            MsgBox("Please enter a valid email address")
            txtTo.Focus()
        ElseIf regexEmailAddress.IsMatch(txtCC.Text) = False Then
            MsgBox("Please enter a valid email address")
            txtCC.Focus()
        ElseIf txtSubject.Text = "" Or cmbEncoding.Text = "" Then
            MsgBox("Please fill in all of the fields")
        Else
            'Database Operations: Add all data to Access Database
            Dim drEmail As DataRow

            drEmail = dsEmail.Tables(0).NewRow()  'Gets a reference to a new row.
            drEmail("fldEmailID") = txtEmailID.Text

            drEmail("fldEmailFrom") = txtFrom.Text
            drEmail("fldEmailTo") = txtTo.Text
            drEmail("fldEmailCC") = txtCC.Text
            drEmail("fldEmailSubject") = txtSubject.Text
            drEmail("fldEmailEncoding") = cmbEncoding.Text
            drEmail("fldEmailDigitalSignature") = chkDigitalSignature.CheckState
            drEmail("fldEmailEncrypt") = chkEncrypt.CheckState
            drEmail("fldEmailAttachments") = txtAttachments.Text

            dsEmail.Tables(0).Rows.Add(drEmail)
            daEmail.Update(dsEmail)
            dsEmail.AcceptChanges()

            'Send Email
            If txtFrom.Text.Length = 0 Then
                MessageBox.Show("Please input From, the format can be test@adminsystem.com or Tester<test@adminsystem.com>")
                Exit Sub
            End If

            If txtTo.Text.Length = 0 And _
            txtCC.Text.Length = 0 Then
                MessageBox.Show("Please input To and Cc, the format can be test@adminsystem.com or Tester<test@adminsystem.com>, please use , or ; to separate multiple addresses")
                Exit Sub
            End If

            btnSendEmail.Enabled = False
            btnCancel.Enabled = True
            m_bcancel = False

            'For evaluation usage, please use "TryIt" as the license code, otherwise the 
            '"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
            '"trial version expired" exception will be thrown.

            'For licensed uasage, please use your license code instead of "TryIt", then the object
            'will never expire
            Dim oMail As SmtpMail = New SmtpMail("TryIt")
            Dim oSmtp As SmtpClient = New SmtpClient
            'To generate a log file for SMTP transaction, please use
            'oSmtp.LogFileName = "c:\smtp.log"

            Dim errStr As String = ""

            Try
                oMail.Reset()
                'If you want to specify a reply address
                'oMail.Headers.ReplaceHeader( "Reply-To: <reply@mydomain>" )

                'If you want to specify a reply address
                'oMail.Headers.ReplaceHeader( "Reply-To: <reply@mydomain>" )

                'From is a MailAddress object
                'The example code
                ' oMail.From = New MailAddress( "Tester", "test@adminsystem.com" )
                ' oMail.From = New MailAddress( "Tester<test@adminsystem.com>" )
                ' oMail.From = New MailAddress( "test@adminsystem.com" )
                oMail.From = New MailAddress(txtFrom.Text)

                'To, Cc and Bcc is a AddressCollection object
                'The example code
                'oMail.To = New AddressCollection( "test1@adminsystem.com, test2@adminsystem.com" )
                'oMail.To = New AddressCollection( "Tester1<test@adminsystem.com>, Tester2<test2@adminsystem.com>")
                oMail.To = New AddressCollection(txtTo.Text)
                'You can add more recipient by Add method
                'oMail.To.Add( new MailAddress( "tester", "test@adminsystem.com"))

                oMail.Cc = New AddressCollection(txtCC.Text)
                oMail.Subject = txtSubject.Text
                oMail.Charset = m_arCharset(cmbEncoding.SelectedIndex, 1)

                'digital signature and encryption
                If Not _Signencrypt(oMail) Then
                    btnSendEmail.Enabled = True
                    btnCancel.Enabled = False
                    Exit Sub
                End If

                Dim basepath As String = Application.ExecutablePath
                Dim pos As Integer = basepath.LastIndexOfAny("/\".ToCharArray())
                If pos <> -1 Then
                    basepath = basepath.Substring(0, pos)
                End If

                Dim body As String = m_htmlDoc.body.innerHTML
                body = body.Replace("[$from]", _EncodeAddress(oMail.From.ToString()))
                body = body.Replace("[$to]", _EncodeAddress(oMail.To.ToString()))
                body = body.Replace("[$subject]", _EncodeAddress(oMail.Subject))
                Dim htmlheader As String = String.Format("<html><title>{0}</title><meta HTTP-EQUIV=""Content-Type"" Content=""text-html; charset={1}""><META content=""MSHTML 6.00.2900.2769"" name=GENERATOR><body>", _
         oMail.Subject, oMail.Charset)

                body = body.Insert(0, htmlheader)
                body += "</body></html>"

                oMail.ImportHtml(body, _
                    Application.ExecutablePath, _
                    ImportHtmlBodyOptions.ImportLocalPictures)

                ' oMail.HtmlBody = textBody.Text

                Dim count As Integer = m_arAttachment.Count
                Dim i As Integer = 0
                For i = 0 To count - 1
                    oMail.AddAttachment(CType(m_arAttachment(i), String))
                Next

                Dim oServer As SmtpServer = New SmtpServer(strServer)
                oServer.Protocol = frmSettings.cmbProtocol.SelectedIndex

                If oServer.Server.Length <> 0 Then
                    If (frmSettings.chkRequiresAuthentication.Checked) Then
                        oServer.User = strEmailUsername
                        oServer.Password = strEmailPassword
                    End If

                    If (frmSettings.chkSSLConnection.Checked) Then
                        oServer.ConnectType = SmtpConnectType.ConnectSSLAuto
                    End If
                Else
                    'To send email to the recipient directly(simulating the smtp server), 
                    'please add a Received header, 
                    'otherwise, many anti-spam filter will make it as junk email.
                    Dim cur As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
                    Dim gmtdate As String = System.DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", cur)
                    gmtdate.Remove(gmtdate.Length - 3, 1)
                    Dim recvheader As String = String.Format("from {0} ([127.0.0.1]) by {0} ([127.0.0.1]) with SMTPSVC;" & vbCrLf & Chr(9) & " {1}", _
                        oServer.HeloDomain, _
                        gmtdate)
                    oMail.Headers.Insert(0, New HeaderItem("Received", recvheader))
                End If

                'Catching the following events is not necessary, 
                'just make the application more user friendly.
                'If you use the object in asp.net/windows service or non-gui application, 
                'You need not to catch the following events.
                'To learn more detail, please refer to the code in EASendMail EventHandler region
                AddHandler oSmtp.OnIdle, AddressOf OnIdle
                AddHandler oSmtp.OnAuthorized, AddressOf OnAuthorized
                AddHandler oSmtp.OnConnected, AddressOf OnConnected
                AddHandler oSmtp.OnSecuring, AddressOf OnSecuring
                AddHandler oSmtp.OnSendingDataStream, AddressOf OnSendingDataStream

                If oServer.Server.Length = 0 And oMail.Recipients.Count > 1 Then
                    'To send email without specified smtp server, we have to send the emails one by one 
                    ' to multiple recipients. That is because every recipient has different smtp server.
                    _DirectSend(oMail, oSmtp)
                Else
                    sbStatus.Text = "Connecting ... "
                    pgSending.Value = 0
                    oSmtp.SendMail(oServer, oMail)
                    MessageBox.Show(String.Format("The message was sent to {0} successfully!", _
          oSmtp.CurrentSmtpServer.Server))
                    sbStatus.Text = "Completed"
                End If
            Catch exp As SmtpTerminatedException
                errStr = exp.Message
            Catch exp As SmtpServerException
                errStr = String.Format("Exception: Server Respond: {0}", exp.ErrorMessage)
            Catch exp As System.Net.Sockets.SocketException
                errStr = String.Format("Exception: Networking Error: {0} {1}", exp.ErrorCode, exp.Message)
            Catch exp As System.ComponentModel.Win32Exception
                errStr = String.Format("Exception: System Error: {0} {1}", exp.ErrorCode, exp.Message)
            Catch exp As System.Exception
                errStr = String.Format("Exception: Common: {0}", exp.Message)
            End Try
            If errStr.Length > 0 Then
                MessageBox.Show(errStr)
                sbStatus.Text = errStr
            End If

            btnSendEmail.Enabled = True
            btnCancel.Enabled = False

            AddNewRecord()

        End If
    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        m_bcancel = True
        btnCancel.Enabled = False
        AddNewRecord()
    End Sub

    Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
        If cmbSelectGroup.Text = "Candidates" Then
            If ds.Tables(0).Rows.Count > 1 Then
                'Since 0 is the first row
                intCurrentIndex = 0
                FillFields()
            ElseIf ds.Tables(0).Rows.Count = 0 Then
                MsgBox("No records exist in database")
            Else
                MessageBox.Show("You are already at the first record.")
            End If
        ElseIf cmbSelectGroup.Text = "Staff" Then
            If dsStaff.Tables(0).Rows.Count > 1 Then
                'Since 0 is the first row
                intCurrentIndexStaff = 0
                FillFieldsStaff()
            ElseIf dsStaff.Tables(0).Rows.Count = 0 Then
                MsgBox("No records exist in database")
            Else
                MessageBox.Show("You are already at the first record.")
            End If
        Else
            MsgBox("No records exist in database")
        End If
    End Sub

    Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
        If cmbSelectGroup.Text = "Candidates" Then
            If intCurrentIndex > 0 Then  'We move back only if we're not at the first row.
                intCurrentIndex = intCurrentIndex - 1  'Subtract one from the current index.
                FillFields()
            ElseIf ds.Tables(0).Rows.Count = 0 Then
                MsgBox("No records exist in database")
            Else
                MessageBox.Show("You are already at the first record.")
            End If
        ElseIf cmbSelectGroup.Text = "Staff" Then
            If intCurrentIndexStaff > 0 Then  'We move back only if we're not at the first row.
                intCurrentIndexStaff = intCurrentIndexStaff - 1  'Subtract one from the current index.
                FillFieldsStaff()
            ElseIf dsStaff.Tables(0).Rows.Count = 0 Then
                MsgBox("No records exist in database")
            Else
                MessageBox.Show("You are already at the first record.")
            End If
        Else
            MsgBox("No records exist in database")
        End If
    End Sub

    Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
        If cmbSelectGroup.Text = "Candidates" Then
            If intCurrentIndex < ds.Tables(0).Rows.Count - 1 Then 'ds.Tables(0).Rows.Count - 1 is the index for the last row
                intCurrentIndex = intCurrentIndex + 1  'Add one to the current index.
                FillFields()
            ElseIf ds.Tables(0).Rows.Count = 0 Then
                MsgBox("No records exist in database")
            Else
                MessageBox.Show("You are already at the last record.")
            End If
        ElseIf cmbSelectGroup.Text = "Staff" Then
            If intCurrentIndexStaff < dsStaff.Tables(0).Rows.Count - 1 Then 'ds.Tables(0).Rows.Count - 1 is the index for the last row
                intCurrentIndexStaff = intCurrentIndexStaff + 1  'Add one to the current index.
                FillFieldsStaff()
            ElseIf dsStaff.Tables(0).Rows.Count = 0 Then
                MsgBox("No records exist in database")
            Else
                MessageBox.Show("You are already at the last record.")
            End If
        Else
            MsgBox("No records exist in database")
        End If
    End Sub

    Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
        If cmbSelectGroup.Text = "Candidates" Then
            If ds.Tables(0).Rows.Count > 1 Then
                intCurrentIndex = ds.Tables(0).Rows.Count - 1 'ds.Tables(0).Rows.Count - 1 is the index for the last row
                FillFields()
            ElseIf ds.Tables(0).Rows.Count = 0 Then
                MsgBox("No records exist in database")
            Else
                MessageBox.Show("You are already at the last record.")
            End If
        ElseIf cmbSelectGroup.Text = "Staff" Then
            If dsStaff.Tables(0).Rows.Count > 1 Then
                intCurrentIndexStaff = dsStaff.Tables(0).Rows.Count - 1 'ds.Tables(0).Rows.Count - 1 is the index for the last row
                FillFieldsStaff()
            ElseIf dsStaff.Tables(0).Rows.Count = 0 Then
                MsgBox("No records exist in database")
            Else
                MessageBox.Show("You are already at the last record.")
            End If
        Else
            MsgBox("No records exist in database")
        End If
    End Sub

    Private Sub cmbSelectGroup_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSelectGroup.SelectedIndexChanged
        If cmbSelectGroup.Text = "Candidates" Then
            'Empty fields
            txtID.Text = ""
            txtFirstName.Text = ""
            txtSurname.Text = ""
            txtEmail.Text = ""
            'Fill fields
            FillFields()
        ElseIf cmbSelectGroup.Text = "Staff" Then
            'Empty fields
            txtID.Text = ""
            txtFirstName.Text = ""
            txtSurname.Text = ""
            txtEmail.Text = ""
            FillFieldsStaff()
        ElseIf cmbSelectGroup.SelectedIndex = -1 Then
            MsgBox("You have not selected a group")
        Else
            MsgBox("No records exist in database")
        End If
    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        attachmentDlg.Reset()
        attachmentDlg.Multiselect = True
        attachmentDlg.CheckFileExists = True
        attachmentDlg.CheckPathExists = True
        If attachmentDlg.ShowDialog() <> Windows.Forms.DialogResult.OK Then
            Exit Sub
        End If

        Dim attachments() As String = attachmentDlg.FileNames
        Dim nLen As Integer = attachments.Length
        Dim i As Integer = 0
        For i = 0 To nLen - 1
            m_arAttachment.Add(attachments(i))
            Dim fileName As String = attachments(i)
            Dim pos As Integer = fileName.LastIndexOf("\")
            If pos <> -1 Then
                fileName = fileName.Substring(pos + 1)
            End If
            txtAttachments.Text += fileName
            txtAttachments.Text += ";"
        Next
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        m_arAttachment.Clear()
        txtAttachments.Text = ""
        htmlEditor.Focus()
    End Sub

    Private Sub btnBold_Click(sender As Object, e As EventArgs) Handles btnBold.Click
        m_htmlDoc.execCommand("Bold", False, Nothing)
        htmlEditor.Focus()
    End Sub

    Private Sub btnItalics_Click(sender As Object, e As EventArgs) Handles btnItalics.Click
        m_htmlDoc.execCommand("Italic", False, Nothing)
        htmlEditor.Focus()
    End Sub

    Private Sub btnUnderline_Click(sender As Object, e As EventArgs) Handles btnUnderline.Click
        m_htmlDoc.execCommand("Underline", False, Nothing)
        htmlEditor.Focus()
    End Sub

    Private Sub btnColour_Click(sender As Object, e As EventArgs) Handles btnColour.Click
        If colorDlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim v As String = String.Format("#{0:x2}{1:x2}{2:x2}", colorDlg.Color.R, _
                 colorDlg.Color.G, _
                 colorDlg.Color.B)
            m_htmlDoc.execCommand("ForeColor", False, v)
        End If
        htmlEditor.Focus()
    End Sub

#Region "Initialize Fonts List"
    Protected Sub InitFonts()
        Dim arFonts() As String = {"Choose Font Style ...", _
                  "Allegro BT", _
                  "Arial", _
                  "Arial Baltic", _
                  "Arial Black", _
                  "Arial CE", _
                  "Arial CYR", _
                  "Arial Greek", _
                  "Arial Narrow", _
                  "Arial TUR", _
                  "AvantGarde Bk BT", _
                  "BankGothic Md BT", _
                  "Basemic", _
                  "Basemic Symbol", _
                  "Basemic Times", _
                  "Batang", _
                  "BatangChe", _
                  "Benguiat Bk BT", _
                  "BernhardFashion BT", _
                  "BernhardMod BT", _
                  "Book Antiqua", _
                  "Bookman Old Style", _
                  "Bremen Bd BT", _
                  "Century Gothic", _
                  "Charlesworth", _
                  "Comic Sans MS", _
                  "CommonBullets", _
                  "CopprplGoth Bd BT", _
                  "Courier", _
                  "Courier New", _
                  "Courier New Baltic", _
                  "Courier New CE", _
                  "Courier New CYR", _
                  "Courier New Greek", _
                  "Courier New TUR", _
                  "Dauphin", _
                  "Dotum", _
                  "DotumChe", _
                  "Dungeon", _
                  "English111 Vivace BT", _
                  "Estrangelo Edessa", _
                  "Fixedsys", _
                  "Franklin Gothic Medium", _
                  "Futura Lt BT", _
                  "Futura Md BT", _
                  "Futura XBlk BT", _
                  "FuturaBlack BT", _
                  "Garamond", _
                  "Gautami", _
                  "Georgia", _
                  "GoudyHandtooled BT", _
                  "GoudyOlSt BT", _
                  "Gulim", _
                  "GulimChe", _
                  "Gungsuh", _
                  "GungsuhChe", _
                  "Haettenschweiler", _
                  "Humanst521 BT", _
                  "Impact", _
                  "Kabel Bk BT", _
                  "Kabel Ult BT", _
                  "Kingsoft Phonetic Plain", _
                  "Latha", _
                  "Lithograph", _
                  "LithographLight", _
                  "Lucida Console", _
                  "Lucida Sans Unicode", _
                  "Mangal", _
                  "Marlett", _
                  "Microsoft Sans Serif", _
                  "MingLiU", _
                  "Modern", _
                  "Monotype Corsiva", _
                  "MS Gothic", _
                  "MS Mincho", _
                  "MS Outlook", _
                  "MS PGothic", _
                  "MS PMincho", _
                  "MS Sans Serif", _
                  "MS Serif", _
                  "MS UI Gothic", _
                  "MT Extra", _
                  "MV Boli", _
                  "Myriad Condensed Web", _
                  "Myriad Web", _
                  "OzHandicraft BT", _
                  "Palatino Linotype", _
                  "PMingLiU", _
                  "PosterBodoni BT", _
                  "Raavi", _
                  "Roman", _
                  "Script", _
                  "Serifa BT", _
                  "Serifa Th BT", _
                  "Shruti", _
                  "Small Fonts", _
                  "Souvenir Lt BT", _
                  "Staccato222 BT", _
                  "Swiss911 XCm BT", _
                  "Sylfaen", _
                  "Symbol", _
                  "System", _
                  "Tahoma", _
                  "Terminal", _
                  "Times New Roman", _
                  "Times New Roman Baltic", _
                  "Times New Roman CE", _
                  "Times New Roman CYR", _
                  "Times New Roman Greek", _
                  "Times New Roman TUR", _
                  "Trebuchet MS", _
                  "Tunga", _
                  "TypoUpright BT", _
                  "Verdana", _
                  "VisualUI", _
                  "Webdings", _
                  "Wingdings", _
                  "Wingdings 2", _
                  "Wingdings 3", _
                  "WP Arabic Sihafa", _
                  "WP ArabicScript Sihafa", _
                  "WP BoxDrawing", _
                  "WP CyrillicA", _
                  "WP CyrillicB", _
                  "WP Greek Century", _
                  "WP Greek Courier", _
                  "WP Greek Helve", _
                  "WP Hebrew David", _
                  "WP IconicSymbolsA", _
                  "WP IconicSymbolsB", _
                  "WP Japanese", _
                  "WP MathA", _
                  "WP MathB", _
                  "WP MathExtendedA", _
                  "WP MathExtendedB", _
                  "WP MultinationalA Courier", _
                  "WP MultinationalA Helve", _
                  "WP MultinationalA Roman", _
                  "WP MultinationalB Courier", _
                  "WP MultinationalB Helve", _
                  "WP MultinationalB Roman", _
                  "WP Phonetic", _
                  "WP TypographicSymbols", _
                  "WST_Czec", _
                  "WST_Engl", _
                  "WST_Fren", _
                  "WST_Germ", _
                  "WST_Ital", _
                  "WST_Span", _
                  "WST_Swed", _
                  "ZapfEllipt BT", _
                  "Zurich Ex BT"}

        Dim i As Integer
        Dim nCount As Integer = arFonts.Length
        For i = 0 To nCount - 1
            cmbFont.Items.Add(arFonts(i))
        Next

        cmbFont.SelectedIndex = 0
        cmbSize.Items.Add("Font Size ... ")
        For i = 1 To 7
            cmbSize.Items.Add(i)
        Next
        cmbSize.SelectedIndex = 0
    End Sub
#End Region

    Private Sub btnInsertPicture_Click(sender As Object, e As EventArgs) Handles btnInsertPicture.Click
        m_htmlDoc.execCommand("InsertImage", True, Nothing)
    End Sub

    Private Sub cmbSize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSize.SelectedIndexChanged
        Dim size As String = cmbSize.Text
        cmbSize.SelectedIndex = 0
        m_htmlDoc.execCommand("fontsize", False, size)
        htmlEditor.Focus()
    End Sub

    Private Sub cmbFont_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbFont.SelectedIndexChanged
        Dim font As String = cmbFont.Text
        cmbFont.SelectedIndex = 0
        m_htmlDoc.execCommand("fontname", False, font)
        htmlEditor.Focus()
    End Sub
    Private Function _EncodeAddress(ByVal v As String) As String
        v = v.Replace(">", "&gt;")
        v = v.Replace("<", "&lt;")
        _EncodeAddress = v
    End Function

    Private Sub htmlEditor_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) Handles htmlEditor.Navigated
        Dim s As New System.Text.StringBuilder()
        s.Append("<div>This sample demonstrates how to send html email.</div><div>&nbsp;</div>")
        s.Append("<div>From: [$from]</div>")
        s.Append("<div>To: [$to]</div>")
        s.Append("<div>Subject: [$subject]</div><div>&nbsp;</div>")
        s.Append("<div>If no sever address was specified, the email will be delivered to the recipient's server directly,")
        s.Append("However, if you don't have a static IP address, ")
        s.Append("many anti-spam filters will mark it as a junk-email.</div><div>&nbsp;</div>")
        s.Append("<div>If ""Digitial Signature"" was checked, please make sure you have the certificate for the sender address installed on ")
        s.Append("Local User Certificate Store.</div><div>&nbsp;</div>")
        s.Append("<div>If ""Encrypt"" was checked, please make sure you have the certificate for recipient address installed on the Local User Certificate Store.</div>")
        m_htmlDoc.body.innerHTML = s.ToString()
    End Sub

#Region "Cross Thread Access Control"
    Private Delegate Sub SetStatusDelegate(ByVal v As String)
    Private Delegate Sub SetProgressDelegate(ByVal sent As Integer, ByVal total As Integer)

    Private Sub _SetStatusCallBack(ByVal v As String)
        sbStatus.Text = v
    End Sub

    Private Sub _SetProgressCallBack(ByVal sent As Integer, ByVal total As Integer)
        Dim t As Long = sent
        t = t * 100
        t = t / total
        Dim x As Integer = t
        pgSending.Value = x

        Dim tick As Long = System.DateTime.Now.Ticks
        ' call DoEvents every 0.2 second 
        If (tick - m_eventtick > 2000000) Then
            ' Do not call DoEvents too frequently in a very fast lan + larg email.
            m_eventtick = tick
            Application.DoEvents()
        End If

    End Sub

    'Why we need to change the list item text by this function.
    'Because with BeginSendMail method, all the events are fired on another
    'thread, to change the list item safety, we used this function to 
    'update list item. more detail, please refer to Control.BeginInvoke method
    'in MSDN
    Private Sub _SetStatus(ByVal v As String)
        If InvokeRequired Then
            Dim args(0) As Object
            args(0) = v

            Dim d As SetStatusDelegate = New SetStatusDelegate(AddressOf _SetStatusCallBack)
            BeginInvoke(d, args)
        Else
            _SetStatusCallBack(v)
        End If
    End Sub
    Private Sub _SetProgress(ByVal sent As Integer, ByVal total As Integer)
        If InvokeRequired Then
            Dim args(1) As Object
            args(0) = sent
            args(1) = total
            Dim d As SetProgressDelegate = New SetProgressDelegate(AddressOf _SetProgressCallBack)
            BeginInvoke(d, args)
        Else
            _SetProgressCallBack(sent, total)
        End If
    End Sub
#End Region

End Class